layui.use(['form', 'table','layuimini', 'layer', 'element'], function () {
    var $ = layui.jquery,
        form = layui.form,
        table = layui.table,
        layer = layui.layer;
        layuimini = layui.layuimini;

    /**
     * 初始化表单，要加上，不然刷新部分组件可能会不加载
     */
    form.render();

    var MapMerchantInfo = {
        id: 'MapMerchantInfoTable'
    };

    $(function() {
        var index = layer.load(2);

        //初始总数据量
        initDataTotal();

        //初始化省份
        var provinceUrl = "/map/publicMapDistrict/provinceList";
        $.get(provinceUrl, {}, function(data){
            layer.close(index);
            if(data.code == "0"){
                var provinceList = data['data'];
                $.each(provinceList, function(index, province) {
                    if(province.adcode == '440000'){ //默认选中广东省
                        $('select#search_province').append($('<option></option>').attr('selected', 'selected').val(province.adcode).text(province.name));
                    }else{
                        $('select#search_province').append($('<option></option>').val(province.adcode).text(province.name));
                    }
                });
            }else{
                layer.msg(data.msg, {icon:2});
            }
            form.render();
            initCity('440000');
        });
    });

    /**
     * 监听省份改变事件
     */
    form.on('select(provinceFilter)', function(data){
        initCity(data.value);
    });

    /**
     * 监听城市改变事件
     */
    form.on('select(cityFilter)', function(data){
        initCityDataTotal(); //初始当前省份城市总数据量(高徳/百度)
    });

    /**
     * 初始总数据量
     */
    function initDataTotal(){
        var totalUrl = "/map/publicIndex/getMerchantInfoTotal";
        $.get(totalUrl, {}, function(data){
            if(data.code == "0"){
                var gdCount = data['gdCount'];
                var bdCount = data['bdCount'];
                $('#data_num').text('高徳(' + gdCount + ') / 百度(' + bdCount + ')');
            }else{
                $('#data_num').text('统计出错');
            }
        });
    }

    /**
     * 初始当前省份城市总数据量(高徳/百度)
     */
    function initCityDataTotal(){
        //获取搜索条件
        var province = $("#search_province").val();
        var city = $("#search_city").val();
        var area = $("#search_area").val();
        var keyword = $("#search_keyword").val();
        var dataSource = $("#search_dataSource").val();
        var serverKey = $("#search_serverKey").val();

        //封装
        var dataObject = {};
        dataObject['province'] = province;
        dataObject['city'] = city;
        dataObject['area'] = area;
        dataObject['keyword'] = keyword;
        dataObject['dataSource'] = dataSource;
        var result = JSON.stringify(dataObject);

        var totalUrl = "/map/publicIndex/getCityGdBdMerchantInfoTotal";
        $.get(totalUrl, {searchParams: result}, function(data){
            if(data.code == "0"){
                var gdCount = data['gdCount'];
                var bdCount = data['bdCount'];
                var address = data['address'];
                $('#city_pc_name').text(address);
                $('#city_data_num').text('高徳(' + gdCount + ') / 百度(' + bdCount + ')');
            }else{
                $('#city_data_num').text('统计出错');
            }
        });
    }

    /**
     * 初始化城市
     */
    function initCity(provinceCode){
        var index = layer.load(2);
        $('#search_city').empty();
        var url = "/map/publicMapDistrict/cityList";
        $.get(url, {provinceCode: provinceCode}, function(data){
            layer.close(index);
            if(data.code == "0"){
                var cityList = data['data'];
                if(cityList.length > 0){
                    $.each(cityList, function(index, city) {
                        if(city.adcode == '440100'){ //默认选中广州市
                            $('select#search_city').append($('<option></option>').attr('selected', 'selected').val(city.adcode).text(city.name));
                        }else{
                            $('select#search_city').append($('<option></option>').val(city.adcode).text(city.name));
                        }
                    });
                }else{ //没有城市则显示省，例如：[台湾]没有城市、区县、街道，[香港特别行政区]/[澳门特别行政区]没有城市(只有区县)
                    $('select#search_city').append($('<option></option>').val(provinceCode).text($('#search_province').find('option:selected').text()));
                }
            }else{
                layer.msg(data.msg, {icon:2});
            }
            form.render();
            initCityDataTotal(); //初始当前省份城市总数据量(高徳/百度)
        });
    }

    // 监听联系我操作
    $("#call-me-btn").on('click', function () {
        MapMerchantInfo.callMeMsg = layer.open({
            //type: 1,
            title: '联系我',
            btn: ['关闭'],
            yes: function(index, layero){
                layer.close(MapMerchantInfo.callMeMsg); //关闭
            }
            ,content: $('#call-me-wechat-content').html() + '<a href="javascript:void(0)" id="call-me-copy-wechat">复制</a>' + '</br>' +
                $('#call-me-qq-content').html() + '<a href="javascript:void(0)" id="call-me-copy-qq">复制</a>'
        });
    });

    /**
     * 监听联系我-复制微信操作
     */
    $(document).on('click', '#call-me-copy-wechat', async function () {
        try {
            if (navigator.clipboard) { //正式环境没有https可能被浏览器禁用
                await navigator.clipboard.writeText($("#call-me-wechat-content .call-me-wechat").text());
            } else { //兼容老版（不推荐）
                var text = $("#call-me-wechat-content .call-me-wechat").text();
                var tempInput = document.createElement("input");
                document.body.appendChild(tempInput);
                tempInput.setAttribute("value", text);
                tempInput.select();
                document.execCommand("copy");
                document.body.removeChild(tempInput);
            }
            layer.close(MapMerchantInfo.callMeMsg); //关闭
            layer.msg('已复制');
        } catch (err) {
            layer.msg('复制失败: ', err);
        }
    });

    /**
     * 监听联系我-复制QQ操作
     */
    $(document).on('click', '#call-me-copy-qq', async function () {
        try {
            if (navigator.clipboard) { //正式环境没有https可能被浏览器禁用
                await navigator.clipboard.writeText($("#call-me-qq-content .call-me-qq").text());
            } else { //兼容老版（不推荐）
                var text = $("#call-me-qq-content .call-me-qq").text();
                var tempInput = document.createElement("input");
                document.body.appendChild(tempInput);
                tempInput.setAttribute("value", text);
                tempInput.select();
                document.execCommand("copy");
                document.body.removeChild(tempInput);
            }
            layer.close(MapMerchantInfo.callMeMsg); //关闭
            layer.msg('已复制');
        } catch (err) {
            layer.msg('复制失败: ', err);
        }
    });

    var column = [
        [
            {type: 'numbers', title: '序号'},
            {field: 'name', title: '商家名称', align: 'center'},
            {field: 'city', title: '地区', align: 'center',
                templet: function (object) {
                    return object.province + object.city + object.area;
                }
            },
            {field: 'address', title: '地址', align: 'center'},
            // {field: 'location', title: '定位', align: 'center'},
            {field: 'tel', title: '电话', align: 'center'},
            {field: 'infoUpdateTime', title: '信息最后更新时间', align: 'center'},
            {field: 'keyword', title: '关键词', align: 'center'},
            // {field: 'type', title: '行业类型', align: 'center'},
            {field: 'dataSource', title: '数据来源', align: 'center',
                templet: function (object) {
                    if('gaode' == object.dataSource){
                        return '<span class="layui-badge layui-bg-blue">高德地图</span>';
                    }else if('baidu' == object.dataSource){
                        return '<span class="layui-badge layui-bg-red">百度地图</span>';
                    }
                }
            }
        ]
    ];

    table.render({
        elem: '#' + MapMerchantInfo.id,
        url: '/map/publicIndex/getGdMerchantInfo',
        toolbar: '#toolbarBtn',
        defaultToolbar: ['filter', 'exports', 'print'],
        cols: column,
        limits: [50, 100, 200, 300, 500, 1000],
        limit: 200,
        height: 'full-xxx', // 使用'full-xxx'确保全屏显示，或者使用足够大的数值如：'1000px'等
        page: true,
        done: function(res, curr, count) {
            if(MapMerchantInfo.msgIndex){
                initDataTotal(); //初始总数据量
                initCityDataTotal(); //初始当前省份城市总数据量(高徳/百度)
                clearInterval(MapMerchantInfo.msgIndexIntervalId); // 停止日志回显定时器
                setTimeout(function() {
                    layer.close(MapMerchantInfo.msgIndex); //关闭重载提示层
                    layer.msg('抓取完成', {
                        icon: 6,
                        shade: 0.3, //遮罩
                        time: 2000 //2秒关闭（如果不配置，默认是3秒）
                    });
                }, 2000);
            }
        }
    });

    // 监听导出数据操作
    $("#data-export-btn").on('click', function () {

        //获取搜索条件
        var province = $("#search_province").val();
        var city = $("#search_city").val();
        // var area = $("#search_area").val();
        var keyword = $("#search_keyword").val();
        var dataSource = $("#search_dataSource").val();
        var serverKey = $("#search_serverKey").val();

        //封装
        var dataObject = {};
        dataObject['province'] = province;
        dataObject['city'] = city;
        // dataObject['area'] = area;
        dataObject['keyword'] = keyword;
        dataObject['dataSource'] = dataSource;
        dataObject['serverKey'] = serverKey;

        var query = JSON.stringify(dataObject);

        //校验数据是否导出来过
        var logIndex = layer.msg('<i class="layui-icon layui-anim layui-anim-rotate layui-anim-loop">&#xe63d;</i> 正在校验数据,请稍后...', {
                //icon: 6,
                shade: 0.3, //遮罩
                time: 20000 //20秒关闭（如果不配置，默认是3秒）
        });
        var logUrl = "/map/publicIndex/checkExportDataLog";
        $.get(logUrl, {searchParams: query}, function(data){
            layer.close(logIndex);
            if(data.code == "0"){
                var result = data['result'];
                if(result === 'error'){
                    layer.confirm(data['msg'], {icon: 3, title:'系统提示',
                        yes: function(index, layero){
                            var downloadUrl = '/map/publicIndex/exportData?searchParams=' + encodeURIComponent(query);
                            window.open(downloadUrl, '_blank');
                            layer.close(index);
                        },
                    });
                }else{
                    layer.msg('校验通过', {icon:6});
                    var downloadUrl = '/map/publicIndex/exportData?searchParams=' + encodeURIComponent(query);
                    window.open(downloadUrl, '_blank');
                }
            }else{
                layer.msg(data.msg, {icon:2});
            }
        });
    });

    // 监听搜索操作
    $("#data-search-btn").on('click', function () {
        //禁用按钮防止多次点击
        if($("#data-search-btn").attr('class') === 'layui-btn layui-btn-disabled'){
            layer.msg('不可频繁操作', {icon: 5});
            return;
        }
        $("#data-search-btn").attr('class', 'layui-btn layui-btn-disabled');

        // 5秒后解禁按钮
        MapMerchantInfo.num = 10;
        MapMerchantInfo.intervalId = setInterval(function() {
            MapMerchantInfo.num--;
            $("#data-search-btn").html('<i class="layui-icon"></i> 获取数据中(' + MapMerchantInfo.num + ')');
            if(MapMerchantInfo.num == 0){
                $("#data-search-btn").attr('class', 'layui-btn');
                $("#data-search-btn").html('<i class="layui-icon"></i> 获取数据');
                // 停止定时器
                clearInterval(MapMerchantInfo.intervalId);
            }
        }, 1000);

        //获取搜索条件
        var province = $("#search_province").val();
        var city = $("#search_city").val();
        var area = $("#search_area").val();
        var keyword = $("#search_keyword").val();
        var dataSource = $("#search_dataSource").val();
        var serverKey = $("#search_serverKey").val();

        //封装
        var dataObject = {};
        dataObject['province'] = province;
        dataObject['city'] = city;
        dataObject['area'] = area;
        dataObject['keyword'] = keyword;
        dataObject['dataSource'] = dataSource;
        dataObject['serverKey'] = serverKey;
        var uniqueID = new Date().getTime(); //生成日志编号
        dataObject['logCode'] = uniqueID;
        MapMerchantInfo.logCode = uniqueID;
        var result = JSON.stringify(dataObject);

        var url = "/map/publicIndex/getCityMerchantInfoTotal";
        $.get(url, {searchParams: result}, function(data){
            if(data.code == "0"){
                var dataCount = data['count'];
                if(dataCount > 0){
                    layer.confirm('请选择抓取方式', {
                        btn: ['信息库中抓取', '重新抓取高徳'] //可以无限个按钮
                        ,btn2: function(index, layero){
                            dataObject['getType'] = '2'; //抓取类型：1信息库中抓取，2重新抓取高徳
                            getDataFun(dataObject)
                        }
                    }, function(index, layero){
                        dataObject['getType'] = '1'; //抓取类型：1信息库中抓取，2重新抓取高徳
                        getDataFun(dataObject)
                    });
                }else{
                    dataObject['getType'] = '2'; //抓取类型：1信息库中抓取，2重新抓取高徳
                    getDataFun(dataObject)
                }
            }else{
                layer.msg(data.msg, {icon:2});
            }
        });
    });

    /**
     * 抓取数据
     * @param getType 抓取类型：1信息库中抓取，2重新抓取高徳
     * @returns {boolean}
     */
    function getDataFun(dataObject) {
        var result = JSON.stringify(dataObject);

        //提示
        var msgClass = 'layui-icon layui-anim layui-anim-rotate layui-anim-loop';
        var msgStyle = 'height: 360px; width:100%; max-width:300px;';
        var msgClass_box = 'overflow: auto;height: 300px;color: #009688;';
        var msgClass_pclass = 'font-size: 14px; text-align: left;border-bottom: 1px solid #009688; padding-top: 5px; padding-bottom:5px;';
        MapMerchantInfo.msgIndex = layer.msg(
            '<div id="msgClass" style="' + msgStyle + '">' +
            '<div style="height: 55px;margin-bottom: 10px;border-bottom: 1px solid #999;font-size: 15px;">' +
            '<i class="' + msgClass + '">&#xe63d;</i> 正在获取数据中(城镇街道地区越多,数据量越大,获取越慢),请稍后...' +
            '</div>' +
            '<div id="msgClassBox" style="' + msgClass_box + '"></div>' +
            '</div>', {
                //icon: 6,
                shade: 0.3, //遮罩
                offset: '150px', //弹框位置：顶部150
                time: 2000000 //2000秒关闭（如果不配置，默认是3秒）
            });
        //添加定时器回显抓取日志
        MapMerchantInfo.msgIndexIntervalId = setInterval(function() {
            var url = "/map/publicMapLog/mapLogList";
            $.get(url, {logCode: MapMerchantInfo.logCode}, function(data){
                if(data.code == "0"){
                    var logList = data['data'];
                    if(logList.length > 0){
                        $.each(logList, function(index, log) {
                            $('#msgClassBox').append($('<p></p>').attr('style', msgClass_pclass).text(log.content));
                            // $('#msgClass').scrollTop($('#msgClass')[0].scrollHeight); //滚动到最底部
                            $('#msgClassBox').animate({ scrollTop: $('#msgClassBox')[0].scrollHeight }, 500); // 滚动到最底部，使用动画效果
                        });
                    }
                }
            });
        }, 600);

        // var msgText = '<span style="font-size: 16px;">' +
        //     '<i class="' + msgClass + '">&#xe63d;</i>  ' +
        //     '<span style="color: red">正在获取数据中<span style="font-weight: bolder;">(城镇街道地区越多,数据量越大,获取越慢)</span>,请稍后...</span>' +
        //     '</span>'
        // MapMerchantInfo.msgIndex = layer.alert(msgText, {
        //     btn: [], //按钮
        //     title: false, //标题
        //     //icon: 1, //提示图标
        //     shade: 0.3, //遮罩
        //     closeBtn: 0 //关闭按钮：0无，1、2
        // });


        //执行搜索重载
        table.reload(MapMerchantInfo.id, {
            page: {
                curr: 1
            }
            , where: {
                searchParams: result
            }
        }, 'data');

        return false;
    }

    // 监听重置操作
    $("#data-reset-btn").on('click', function () {

        //初始化
        $("#search_province").val("广东省");
        $("#search_city").val("广州市");
        $("#search_area").val("荔湾区");
        $("#search_keyword").val("奶茶店");
        $("#search_dataSource").val("gaode");
        $("#search_serverKey").val("");

        form.render();

        //封装
        var dataObject = {};
        dataObject['province'] = "广东省";
        dataObject['city'] = "广州市";
        dataObject['area'] = "荔湾区";
        dataObject['keyword'] = "奶茶店";
        dataObject['dataSource'] = "gaode";
        dataObject['serverKey'] = "";
        var result = JSON.stringify(dataObject);

        //执行搜索重载
        table.reload(MapMerchantInfo.id, {
            page: {
                curr: 1
            }
            , where: {
                searchParams: result
            }
        }, 'data');

        return false;
    });

    //监听表格复选框选择
    // table.on('checkbox(currentTableFilter)', function (obj) {
    //     console.log(obj)
    // });

    //监听工具条
    table.on('tool(' + MapMerchantInfo.id + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'delete') {

        }
    });

});